package com.example.tweetfeed;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;

public class TwitterFetcher extends IntentService {
//consts
	public static final String TFRM_BROADCAST = "com.example.tweetfeed.TFRM_BROADCAST";
	public static final String QUERY = "com.example.tweetfeed.QUERY";
	public static final String QUERY_TKN = "com.example.tweetfeed.QUERY_TKN";
	public static final String RESULT_ERROR = "com.example.tweetfeed.RESULT";
	public static final String RESULT_TWEET = "com.example.tweetfeed.RESULT_TWEET";
	
	private static final String TWITTER_APP_NAME = "twitter-fetcher-test";
	private static final String TWITTER_TOKEN_KEY = "NXJJcDl3bmx0VmxKMVVyVVFPZGQxczh2azp6ZFJxajhzNzJ0QnlyMjUwTDZ6dEJRbFJueW96cWt1Y2FnZnF5ekhCZWZraGVWUVhHNw==";
	public static final String TWITTER_QUERY_URL = "https://api.twitter.com/1.1/search/tweets.json?q=";
	
	public TwitterFetcher() {
		super("TwitterFetcher");
	}
	
	public static TwitterBearerToken getToken() {
		return new TwitterBearerToken(TWITTER_APP_NAME,TWITTER_TOKEN_KEY);
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
		String query = intent.getStringExtra(QUERY);
		String tkn = intent.getStringExtra(QUERY_TKN);
		searchOnTwitter(query, tkn);
	}
	
	void searchOnTwitter(String queryParam, String bToken) {
		try {
			String encodedParam = URLEncoder.encode(queryParam, "UTF-8");
			String queryUrl = TWITTER_QUERY_URL + encodedParam;
			
			HttpClient client = new DefaultHttpClient();
			HttpGet queryget = new HttpGet(queryUrl);
			queryget.addHeader("User-Agent", TWITTER_APP_NAME);
			queryget.addHeader("Authorization", "Bearer " + bToken);
			
			HttpResponse response = client.execute(queryget);
			if (response.getStatusLine().getStatusCode() == 200) {
				JSONObject resp = getJsonContent(response);
				broadcastResult(getResultTweets(resp));
			}
		} catch (Exception e) {
			e.printStackTrace();
			broadcastError();
		}
	}
	
	private JSONObject getJsonContent(HttpResponse response) throws Exception {
		InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        
        String all = "", line = null;
        while ((line = reader.readLine()) != null) {
        	all += line;
        }
        return new JSONObject(all);
	}
	
	private ArrayList<Tweet> getResultTweets(JSONObject result) throws Exception {
		ArrayList<Tweet> ret = new ArrayList<Tweet>();
		JSONArray vec = result.getJSONArray("statuses");
		for(int i=0; i<vec.length(); i++) {
			ret.add(new Tweet(vec.getJSONObject(i)));
		}
		return ret;
	}
	
	void broadcastResult(ArrayList<Tweet> result) {
		Intent intent = new Intent(TFRM_BROADCAST);
		intent.putExtra(RESULT_ERROR, false);
	    intent.putParcelableArrayListExtra(RESULT_TWEET, result);
	    sendBroadcast(intent);
	}
	
	void broadcastError() {
		Intent intent = new Intent(TFRM_BROADCAST);
	    intent.putExtra(RESULT_ERROR, true);
	    sendBroadcast(intent);
	}
}
